/*
 * author : Dinh Ngoc Tuan Vu (A0092633)
 */
package sg.edu.nus.iss.team4ft.service;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

import sg.edu.nus.iss.team4ft.util.AccountIOService;
import sg.edu.nus.iss.team4ft.util.AppConstant;

public class CallService extends Feature implements UsageChargable, Serializable {
	private static final long serialVersionUID = 1L;
	private ArrayList<Call> calls = new ArrayList<Call>(); 
	
	private CallService(CallService callService) throws CloneNotSupportedException{
		super(callService);
		this.calls = new ArrayList<Call>(callService.calls);
	}
	
	public CallService(Date startDate, FeatureCode featureCode, Plan plan) throws IOException{
		super(startDate, featureCode);
		
		if(getFeatureCode() == FeatureCode.LocalCall){
			super.setServiceName(AppConstant.LOCAL_CALL_FEATURE);
			setIsDefaultService(true);
		}
		else if(getFeatureCode() == FeatureCode.InternationalCall)
			super.setServiceName(AppConstant.INTERNATIONAL_CALL_FEATURE);
		else if(getFeatureCode() == FeatureCode.RoamingCall)
			super.setServiceName(AppConstant.ROAMING_CALL_FEATURE);
		
		setPlan(plan);
		RateTable rt = new RateTable();
		
		if(getPlan() != null)
		{
			//get the 
			Double d = 0.0;
			try {
				d = rt.getChargePerUnit(getPlan().getPlanCode(), featureCode);
			} catch (IOException e) {
				throw e;
			}
			setChargePerUnit(d);
			
			try {
				d = rt.getSubscriptionCharge(getPlan().getPlanCode(), featureCode);
			} catch (IOException e) {
				throw e;
			}
			setSubscriptionCharge(d);
		}
	}

	@Override
	public Double calculateMonthlyUsage(Date forDate) throws NullPointerException, IOException, ParseException {
		calls = AccountIOService.getCallTransactions();
		double totalAmount = 0.0;
		VoicePlan vp = null;
		if(this.getPlan() instanceof VoicePlan)
			vp = (VoicePlan)this.getPlan();
		calls = AccountIOService.getCallTransactions();
		//calculate call charge for all the calls
		if(vp != null){
			for (Call c : calls) {
				if(c.getTelephoneNumber().equals(vp.getTelephoneNumber()) && c.canInclude(forDate) && c.getCallType() == this.getFeatureCode()){
					c.setChargePerUnit(getChargePerUnit());
					totalAmount += c.calculateCallCharge();
				}
			}
		}
		
		return totalAmount;
	}	
	
	@Override
	public CallService clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return new CallService(this);
	}
}
